package com.cupster.func_db_greendao;

//greendao_step8:编写dao管理类

import android.content.Context;

import com.cupster.func_db_greendao.auto.DaoMaster;
import com.cupster.func_db_greendao.auto.DaoSession;

import org.greenrobot.greendao.query.QueryBuilder;

/**
 *
 */
public class DaoManager {

    private static final String TAG = "DaoManager";
    public static final String DB_NAME ="demo_db";
    public static boolean SHOW_LOG = false;

    //====================== code part1:单例 begin ======================
    private Context mContext;

    private volatile static DaoManager mDaoManager = null;

    private static DaoMaster mDaoMaster = null;
    private static DaoMaster.DevOpenHelper mDaoMasterHelper = null;
    private static DaoSession mDaoSession ;

    public static DaoManager getInstance(Context appContext){
        if (mDaoManager == null){
            mDaoManager = new DaoManager(appContext);
        }
        return  mDaoManager;
    }

    private DaoManager(Context context){
        mContext = context;
    }

    //====================== code part1:单例 end ======================



    //======================  code part2: db begin ======================
    public DaoMaster getDaoMaster(){
        if (mDaoMaster == null){
            mDaoMasterHelper = new DaoMaster.DevOpenHelper(mContext ,DB_NAME ,null);
            mDaoMaster = new DaoMaster(mDaoMasterHelper.getWritableDb());
        }
        return mDaoMaster;
    }

    public DaoSession getDaoSession(){
        if (mDaoSession == null){
            if (mDaoMaster == null ){
                getDaoMaster();
            }
            mDaoSession = mDaoMaster.newSession();
        }
        return mDaoSession;
    }

    public void debug(){
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
        SHOW_LOG = true;
    }

    public void closeConnection(){
        closeHelper();
        clearDaoSession();
    }

    private void closeHelper() {
        if (mDaoMasterHelper != null){
            mDaoMasterHelper.close();
            mDaoMasterHelper = null;
        }
    }

    private void clearDaoSession() {
        if (mDaoSession != null){
            mDaoSession.clear();
            mDaoSession = null;
        }
    }

    //====================== code part2:db end ======================


}
